package main
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	
	import assists.log.Log;
	import assists.serialization.json.JSON;
	
	import inerface.IMessage;
	
	import message.Message;

	/**
	 * 
	 * @author clouree
	 * 
	 */	
	public class Server
	{
		private var _socket:Socket = new Socket();
		private var _callBackFuncs:Object = {};
		private var _messagesList:MessageAllList = new MessageAllList();
		private var _delayMessageList:Array = [];//尚未建立连接的时候 要发送的消息
		public function Server()
		{
			addEventListener();
		}
		
		public function send(message:IMessage):void
		{
			if(!startConnect() || _delayMessageList.length > 0)
			{
				_delayMessageList.push(message);
			}else
			{
				sendMessage(message);
			}
		}
		
		private function sendMessage(message:IMessage):void
		{
			trace("发送消息：" +　assists.serialization.json.JSON.encode(message));
			_socket.writeUTFBytes(assists.serialization.json.JSON.encode(message));
			_socket.flush();
		}
		
		private function startConnect():Boolean
		{
			if(_socket.connected) return true;
			_socket.connect(ClientConstants.SERVER_IP,6000);
			return false;
		}
		
		private function addEventListener():void
		{
			_socket.addEventListener(Event.CONNECT,connectHandler);
			_socket.addEventListener(ProgressEvent.SOCKET_DATA,recMessageHandler);
			_socket.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
		}
		
		protected function errorHandler(event:IOErrorEvent):void
		{
			Log.trace("connet error" + event.errorID);
		}
		
		protected function recMessageHandler(event:ProgressEvent):void
		{
			var str:String = _socket.readUTFBytes(_socket.bytesAvailable);
			trace("receive:" + str);
			var info:Object = assists.serialization.json.JSON.decode(str);
			var cls:Class = _messagesList.messageList[info.id];
			var mes:Message = new cls();
			mes.decodeObj(info);
			excuteCallBack(mes);
		}
		
		private function excuteCallBack(value:*):void
		{
			if(!_callBackFuncs[value.id]) return;
		   for(var i:int=0;i<_callBackFuncs[value.id].length;i++)
		   {
			   _callBackFuncs[value.id][i](value);
		   }
		}
		
		protected function connectHandler(event:Event):void
		{
			trace("connect success");
			if(_delayMessageList.length == 0) return;
			for(var i:int = 0;i<_delayMessageList.length;i++)
			{
				sendMessage(_delayMessageList[i]);
			}
			_delayMessageList = [];
		}
		
		public function registerMessageHandler(messageID:uint,callBack:Function):void
		{
			if(_callBackFuncs[messageID])
			{
				_callBackFuncs[messageID].push(callBack);
			}else
			{
				_callBackFuncs[messageID] = [callBack];
			}
			
			
		}
		
		public function cancelMessageHandler(messageID:uint,callBack:Function):void
		{
			var list:Array = _callBackFuncs[messageID];
			for(var i:int=0;i<list.length;i++)
			{
				if(list[i] == callBack)
				{
					list.splice(i,1);
					return;
				}
			}
		}
		
	}
}